var co = require('co');
var moment = require("moment");
var fs = require('fs');
var formidable = require('formidable');
var seqModule = require('../../models/index');
var db = new seqModule();
var util = require('../../common/util');
var speakHostController = {
    getSpeakHostPage: function (req, res) {
        co(function () {
            var page = parseInt(req.query.page);
            var params = {};
            var paramT = {};
            if (req.query.pTitle != undefined) {
                params["$or"] = { "name": { "$like": "%" + req.query.pTitle + "%" }, "tel": { "$like": "%" + req.query.pTitle + "%" } ,"hospitalName":{ "$like": "%" + req.query.pTitle + "%" }};
            }
            if(req.query.type != undefined){
                params.type = parseInt(req.query.type);
            }
            paramT["where"] = params;
            paramT["order"] = [["name",'ASC'],["createTime", 'DESC']];
            if (req.query.page != undefined && req.query.rows != undefined) {
                paramT["offset"] = parseInt(req.query.page);
                paramT["limit"] = parseInt(req.query.rows);
            }
            db.speakHostModule.findAndCountAll(paramT).then(function (result) {
                result.page = page;
                res.status(200).json(result);
            });
        }).catch(function (e) {
            res.status(500).json({"message":"服务异常！"});
            console.log(e);
        })
    },  
    getSpeakHostById: function (req, res) {
        co(function () {
            var paramT = {};
            paramT.where = req.params;
            db.speakHostModule.findOne(paramT).then(function (result) {
                res.status(200).json(result);
            });
        }).catch(function (e) {
            res.status(500).json({"message":"服务异常！"});
            console.log(e);
        })
    },  
    addSpeakHost: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/headImg";
                form.type = true;
                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
    
                form.parse(req, function (err, fields, files) {
                   if(files.headImg != "" && files.headImg != undefined  && files.headImg != null){
                        var imgType=files.headImg.name.split(".");
                        files.headImg.name="headImg_"+moment().format("YYYYMMDDHHmmss")+"."+imgType[imgType.length-1];
                        fs.renameSync(files.headImg.path, form.uploadDir + "/" + files.headImg.name);
                        fields["headImg"]=files.headImg.name;
                    }
                    fields.id = util.getUUID();
                    fields.createTime = util.getNowTime();
                    db.speakHostModule.create(fields).then(function (results) {
                        res.redirect(util.getIP()+'meetSchedule/speakHostList.html');
                    });
                });
            }
        }).catch(function(e) {
            res.json({'success':false,'msg':'添加失败'});
            console.log(e);
        })
    },
    updateSpeakHost: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/headImg";
                form.type = true;
                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                   if(files.headImg != "" && files.headImg != null && files.headImg.name != undefined && files.headImg.name != "" && files.headImg.name != undefined  && files.headImg.name != null){
                        var imgType=files.headImg.name.split(".");
                        files.headImg.name="headImg_"+moment().format("YYYYMMDDHHmmss")+"."+imgType[imgType.length-1];
                        fs.renameSync(files.headImg.path, form.uploadDir + "/" + files.headImg.name);
                        fields["headImg"]=files.headImg.name;
                    }
                    var paramT = {};
                    paramT.where = req.params;
                    db.speakHostModule.update(fields,paramT).then(function (results) {
                        res.redirect(util.getIP()+'meetSchedule/speakHostList.html');
                    });
                });
            }
        }).catch(function(e) {
            res.json({'success':false,'msg':'添加失败'});
            console.log(e);
        })
    },
    delSpeakHostByIds: function (req, res) {
        co(function () {
            var paramT = {};
            var paramU = {};
            var StringId = req.query.params;//传过来的params是以‘,’隔开的字符串
            var arr = StringId.split(",");
            paramU['id'] = [arr];
            paramT['where'] = paramU;
            //destroy、方法就是删除记录的方法 paramT是删除条件
            db.speakHostModule.destroy(paramT).then(function (results) {
                res.status(200).json(results);
            });
        }).catch(function (e) {
            res.status(500).json({"message":"服务异常！"});
            console.log(e);
        })
    }
}
module.exports = speakHostController;